﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Bittorrent.Client.Tracker {
    public class BinaryPeer : IPeer {
        public BinaryPeer(byte[] data) {
            if (data.Length != 6)
                throw new ArgumentException(ErrorResource.BinaryPeerSizeErrorMessage);

            PeerId = string.Empty;
            PeerEndPoint = GetPeerEndPoint(data);
        }

        /// <summary>
        /// The peer's self-selected ID (in compact mode this string is empty).
        /// </summary>
        public string PeerId { get; private set; }

        /// <summary>
        /// Connection EndPoint (IPAddress and port) for the peer.
        /// </summary>
        public IPEndPoint PeerEndPoint { get; private set; }

        private static IPEndPoint GetPeerEndPoint(byte[] data) {
            using (var memory = new MemoryStream(data)) {
                var reader = new BinaryReader(memory);

                var ip = new byte[4];
                reader.Read(ip, 0, 4);
                var port = new byte[4];
                reader.Read(port, 2, 2);

                var ipAddress = new IPAddress(ip);

                if (BitConverter.IsLittleEndian)
                    Array.Reverse(port);

                int portValue = BitConverter.ToInt32(port, 0);

                return new IPEndPoint(ipAddress, portValue);
            }
        }
    }
}
